<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use HyperDown\Parser;
use Laravel\Scout\Searchable;

class Article extends Base
{
	use Searchable;
	// 软删除
	use SoftDeletes;
	
	//
	
	/**
	 * 禁止被批量赋值的字段
	 *
	 * @var array
	 */
	protected $guarded = [];
	
	/**
	 * 索引的字段,全文搜索
	 *
	 * @return array
	 */
	public function toSearchableArray()
	{
		return $this->only('id', 'title', 'keywords', 'description', 'markdown');
	}
	
	/**
	 * 关联标签表
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function tag()
	{
		return $this->belongsToMany(Tag::class, "article_tags");
	}
	
	/**
	 * 关联评论表
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function comment()
	{
		return $this->hasMany(Comment::class);
	}
	
	/**
	 * 关联分类表
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
	 */
	public function category()
	{
		return $this->belongsTo(Category::class);
	}
	
	public function storeData($data)
	{
		
		$data['html'] = self::markdown_to_html($data['markdown']);
		if (!$data['description']) {
			$description = strip_tags($data['html']);
			//            dd($description);
			//使用mb_substr截取中文
			$data['description'] = mb_substr($description, 0, 200);
		}
		//        dd($data['description']);
		$tags_ids = $data['tag_ids'];
		unset($data['tag_ids']);
		//根据是否有id判断修改还是添加
		if (isset($data['id']) && $data['id']) {
			//            $result=$this->where('id',$data['id'])->update($data);
			$a = $this->find($data['id']);
			$a->forceFill($data);
			//            $a->markdown=$data['markdown'];
			$result = $a->save();
		} else {
			$result = $this->create($data);
		}
		if ($result) {
			if (isset($data['id']) && $data['id']) {
				//修改之前先删除原本所有的关联标签
				ArticleTag::where("Article_id", $data['id'])->forceDelete();
				//添加文章标签
				ArticleTag::addArticleTag($data['id'], $tags_ids);
			} else {
				//添加文章标签
				ArticleTag::addArticleTag($result->id, $tags_ids);
			}
		}
	}
	
	/**
	 * markdown内容转Html
	 * @param $markdown
	 * @return string
	 */
	public static function markdown_to_html($markdown)
	{
		//        $Parsedown = new Parsedown();
		//
		//        return $Parsedown->text($markdown);
		$parser = new Parser();
		return $parser->makeHtml($markdown);
	}
	
	public function searchArticle($keywords)
	{
		try {
			$articles = Article::search($keywords)->orderBy("created_at", "desc")->paginate(10);
			//如果全文搜索没有搜到结果，降级使用sql模糊搜索
			if ($articles->isEmpty()) {
				$articles = $this->searchArticleByLike($keywords);
			}
		} catch (\Exception $e) {
			$articles = $this->searchArticleByLike($keywords);
		}
		return $articles;
	}
	
	public function searchArticleByLike($keywords)
	{
		$articles = $this->select('id', 'category_id', 'title',
		                          'author', 'description', 'cover',
		                          'is_top', 'created_at')
			->where("title", "like", "%$keywords%")
			->orWhere("description", "like", "%$keywords%")
			->orWhere("markdown", "like", "%$keywords%")
			->orderBy("created_at", "desc")
			->paginate(10);
		return $articles;
	}
}
